package view;

import java.awt.Color;
import java.awt.GridLayout;

import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import model.Cell;
import model.CurrentSlot;
import model.Sheet;

import xl.Address;
import xl.Adjustment;
import xl.NumberAdjustment;

public class SheetView extends JPanel implements Observer {
    private static Adjustment adjustment = new NumberAdjustment(14, 2);
    private SlotView slotView[][];
    private int rows, cols;
    private Sheet sheet;

    public SheetView(int rows, int cols, CurrentSlot currentSlot) {
        this.rows = rows;
        this.cols = cols;
        slotView = new SlotView[rows][cols];
        setLayout(new GridLayout(rows + 1, cols, 1, 1));
        for (int j = 0; j < cols; j++) {
            JLabel lbl = new JLabel(String.valueOf((char) (j + 'A')),
                    SwingConstants.CENTER);
            lbl.setBackground(Color.LIGHT_GRAY);
            lbl.setOpaque(true);
            add(lbl);
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                SlotView slotViewIj = new SlotView(new Address(i,j), currentSlot);
                add(slotViewIj);
                slotView[i][j] = slotViewIj;
            }
        }
        currentSlot.setCurrent(slotView[0][0]);
        currentSlot.updateCurrent(slotView[0][0]);
        setBackground(Color.BLACK);
    }
    
    public void setSheet(Sheet sheet) {
    	this.sheet = sheet;
    }
    
	public void update(Observable o, Object arg) {
		if (arg instanceof HashMap) {
			HashMap<Address, Cell> hMap = (HashMap)arg;

			Cell currCell;
			for (int i=0 ; i<rows ; i++) {
				for (int k=0 ; k<cols ; k++) {
					currCell = hMap.get(new Address(i, k));
					if (currCell != null) {
						slotView[i][k].setText(currCell.parse(sheet));
					} else {
						slotView[i][k].setText("");
					}
				}
			}
		}
	}
}
